module.exports = app => {
  const express = require('express')
  const router = express.Router()

  //新建电影信息
  router.post('/create', async (req, res) => {
    const model = await req.Model.create(req.body)
    res.send(model)
  })
  //获取电影详情(编辑界面)
  router.get('/item/:id', async (req, res) => {
    const item = await req.Model.findById(req.params.id)
    res.send(item)
  })
  //修改电影详情(编辑界面)
  router.post('/item/:id', async (req, res) => {
    const item = await req.Model.findByIdAndUpdate(req.params.id, req.body)
    res.send(item)
  })
  //获取电影列表
  router.get('/list', async (req, res) => {
    const list = await req.Model.find().limit(9)
    res.send({
      code: 200,
      msg: "success",
      list
    })
  })
  //删除电影列表项(列表界面)
  router.post('/list/:id', async (req, res) => {
    const item = await req.Model.findByIdAndDelete(req.params.id, req.body)
    res.send({
      success: true,
      msg: "删除成功"
    })
  })
  //获取喜欢列表(按分数排序)
  router.get('/hots', async (req, res) => {
   
    const hots = await req.Model.find().sort({'score': -1}).limit(6)
    let newhot = hots.sort(() => Math.random() - 0.5); 
    res.send({
      code: 200,
      msg: "success",
      hots: newhot
    })
  })

  //获取搜索列表(按分数排序)
  router.get('/pulldown', async (req, res) => {
    let page = req.query.page - 1;
    let pageSize = +req.query.pageSize || 9;
    const count = await req.Model.find().count();
    const total = Math.ceil(count / pageSize);
    const pull = await req.Model.find().skip(page*pageSize).limit(pageSize).sort({'score': -1});

    res.send({
      code: 200,
      msg: "success",
      page: page+1,
      total: total,
      count: count,
      list: pull
    })
  })

  router.get('/search', async (req, res) => {
    let keywords = req.query.keywords || ''
    let search = ''
    if(keywords){
      search = await req.Model.find({movieName:{$regex: keywords}});
    }else{
      search = await req.Model.find();
    }
    res.send({
      code: 200,
      msg: "success",
      list: search
    })
  })
  //获取电影详情(编辑界面)
  router.get('/info', async (req, res) => {
    const movieId = req.query.movieId
    const item = await req.Model.findOne({movieId: movieId})
    res.send({
      code: 200,
      msg: "success",
      item
    })
  })
  

  
  app.use('/movie/api/rest/:resource', async (req, res, next) => {
    const modelName = require('inflection').classify(req.params.resource)
    req.Model = require(`../../models/${modelName}`)
    next()
  },router)


  //图片上传
  const multer = require('multer')
  const upload = multer({dest: __dirname + '/../../uploads'})
  app.use('/movie/api/upload', upload.single('file'), async (req, res) => {
    const file = req.file
    file.url = `http://movie.qianheye.cn/uploads/${file.filename}`
    // file.url = `http://localhost:3030/uploads/${file.filename}`
    res.send(file)
  })
}